package com.tanhua.server.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.common.mapper.UserInfoMapper;
import com.tanhua.common.pojo.User;
import com.tanhua.common.pojo.UserInfo;
import com.tanhua.common.utils.UserThreadLocal;
import com.tanhua.dubbo.server.pojo.RecommendUser;
import com.tanhua.dubbo.server.vo.PageInfo;

import com.tanhua.server.vo.PageResult;
import com.tanhua.server.vo.RecommendUserQueryParam;
import com.tanhua.server.vo.TodayBest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;

/**
 * @Auther: you
 * @Date: 2021/05/29/20:12
 * @Description:
 */
@Service
public class TodayBestService {
    @Autowired
    private RecommendUserService recommendUserService;
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private UserInfoService userInfoService;

    @Value("${tanhua.sso.default.user}")
    private Long defaultId;

    public TodayBest queryTodayBest() {
        //1.token令牌校验
        User user = UserThreadLocal.get();

        //2. 从MongoDB中查询今日佳人(推荐用户)
        TodayBest todayBest= recommendUserService.queryTodayBest(user.getId());
        if (todayBest==null){
            //默认给一个推荐用户
            todayBest.setId(defaultId);
            todayBest.setFateValue(80);//缘分值，此时默认80分
        }

        //3.从mysql中查询用户信息，并补全推荐用户信息

        UserInfo userInfo = userInfoService.queryUserInfoByUserId(todayBest.getId());


        todayBest.setAge(userInfo.getAge());
        todayBest.setAvatar(userInfo.getLogo());
        todayBest.setGender(userInfo.getSex().getValue()==1?"man":"woman");   //返回性别：man/woman ,需要转换，枚举
        todayBest.setNickname(userInfo.getNickName());
        todayBest.setTags(StringUtils.split(userInfo.getTags(),","));//标签

        return todayBest;

    }

    public PageResult queryRecommendation(RecommendUserQueryParam param) {
        //1.token令牌校验
        User user = UserThreadLocal.get();

        PageResult pageResult = new PageResult();
        pageResult.setPage(param.getPage());
        pageResult.setPagesize(param.getPagesize());

        //2. 从MongoDB中查询推荐列表
        PageInfo<RecommendUser> recommendUserPageInfo = recommendUserService.queryRecommendation(user.getId(), param.getPage(), param.getPagesize());
        if (recommendUserPageInfo.getRecords()==null){
            //没有查询到推荐列表
            return pageResult;

        }

        //填充用户信息
        //收集推荐用户的id(使用set集合，特性：不重复id)
        Set<Long> userIds=new HashSet<>();

        for (RecommendUser record : recommendUserPageInfo.getRecords()) {
            userIds.add(record.getUserId());
        }

        //3.从mysql中查询用户信息，并补全推荐用户信息

        QueryWrapper<UserInfo> queryWrapper=new QueryWrapper<>();
        //查询推荐用户的id
        queryWrapper.in("user_id",userIds);

        //查询条件（man/woman）
        if (StringUtils.isNotEmpty(param.getGender())){
//            queryWrapper.eq("sex",param.getGender()=="man" ? 1:2);
        }
        //查询所在城市
        if (StringUtils.isNotEmpty(param.getCity())){
//            queryWrapper.eq("city",param.getCity());
        }
        //查询所处年龄范围
        if (param.getAge()!=null){
            //小于等于  lt:小于  gt:大于  ge:大于等于
//            queryWrapper.le("age",param.getAge());
        }

        List<UserInfo> userInfoList = userInfoService.queryUserInfoList(queryWrapper);
        //没有查询到用户的基本信息
        if (CollectionUtils.isEmpty(userInfoList)){
            return pageResult;
        }

        List<TodayBest> todayBests=new ArrayList<>();

        for (UserInfo userInfo : userInfoList) {
            //补全用户信息
            TodayBest todayBest = new TodayBest();
            todayBest.setId(userInfo.getId());
            todayBest.setAge(userInfo.getAge());
            todayBest.setAvatar(userInfo.getLogo());
            todayBest.setGender(userInfo.getSex().getValue()==1?"man":"woman");   //返回性别：man/woman ,需要转换，枚举
            todayBest.setNickname(userInfo.getNickName());
            todayBest.setTags(StringUtils.split(userInfo.getTags(),","));//标签


            //填充缘分值
            for (RecommendUser record : recommendUserPageInfo.getRecords()) {
                if (record.getUserId()==userInfo.getUserId()){//向下取整
                    todayBest.setFateValue((int)Math.floor(record.getScore()));
                    break;
                }
            }
            //添加到集合中
            todayBests.add(todayBest);
        }

        //根据缘分值，给推荐用户集合降序排序
        Collections.sort(todayBests,(o1, o2) -> o2.getFateValue()-o1.getFateValue());

        pageResult.setItems(todayBests);
        return pageResult;
    }
}
